import clsx from 'clsx';
import { HexAlphaColorPicker, HexColorInput } from 'react-colorful';
import { useControlledState } from '@/hooks';
import { useAppStore } from '@/stores';
import { Popover } from '../popover';
import type { IPopoverProps } from '../popover';
import './index.less';

export type IColorfulPopoverProps = IPopoverProps & {
  showContentWrap?: boolean;
  color?: string;
  contentWrapClassName?: string;
  onChange?: (color?: string) => void;
};

export type IColorfulListProps = {
  className?: string;
  style?: React.CSSProperties & { '--width': string; '--height': string };
  onChange?: (value: string) => void;
  value?: string;
};

export const ColorfulList = (props: IColorfulListProps) => {
  const map = useAppStore.use.map()!;
  const { onChange, value, className, ...resetProps } = props;
  const [color, setColor] = useControlledState(value, (v) => v && onChange?.(v));

  const onClick = (c: string) => {
    if (c !== color) setColor(c);
  };

  return (
    <div {...resetProps} className={clsx('smap-colorful-list', className)}>
      {map.iconImage.iconColorList.map((c) => (
        <div key={c} className={clsx({ active: color === c })} onClick={() => onClick(c)}>
          <div style={{ background: c }} />
        </div>
      ))}
    </div>
  );
};

export const ColorfulPopover = (props: IColorfulPopoverProps) => {
  const { showContentWrap, contentWrapClassName, color: propColor, onChange: propOnChange, children, ...restProps } = props;
  const [color, setColor] = useControlledState(propColor, propOnChange);

  const onChange = (color?: string) => {
    setColor(color);
  };

  const render = () => {
    return showContentWrap ? <div className={contentWrapClassName}>{children}</div> : children;
  };

  return (
    <Popover
      trigger="click"
      {...restProps}
      className={clsx('smap-colorful-popover', restProps.className)}
      content={
        <>
          <HexAlphaColorPicker color={color} onChange={onChange} />
          <HexColorInput prefixed prefix="#" alpha className="smap-colorful-input" color={color} onChange={onChange} />
          <ColorfulList onChange={onChange} />
        </>
      }
    >
      {render()}
    </Popover>
  );
};
